package net.documentshare.docu;

import java.io.InputStream;
import java.util.Arrays;
import java.util.Map;

import net.documentshare.common.CommonUtils;
import net.documentshare.common.ECommonType;
import net.documentshare.documentconfig.DocumentConfigMgr;
import net.documentshare.documentconfig.StorageBean;
import net.documentshare.i.ICommonBeanAware;
import net.documentshare.impl.AbstractAttention;
import net.documentshare.mytag.ETagType;
import net.documentshare.mytag.MyTagBean;
import net.documentshare.mytag.MyTagUtils;
import net.documentshare.utils.ItSiteUtil;
import net.documentshare.utils.NumberUtils;
import net.simpleframework.ado.IDataObjectValue;
import net.simpleframework.ado.db.ExpressionValue;
import net.simpleframework.ado.db.ITableEntityManager;
import net.simpleframework.ado.db.event.TableEntityAdapter;
import net.simpleframework.content.AbstractMgrToolsAction;
import net.simpleframework.content.EContentType;
import net.simpleframework.content.IContentApplicationModule;
import net.simpleframework.core.ado.IDataObjectQuery;
import net.simpleframework.core.id.ID;
import net.simpleframework.core.id.LongID;
import net.simpleframework.organization.IJob;
import net.simpleframework.organization.IUser;
import net.simpleframework.organization.OrgUtils;
import net.simpleframework.organization.account.AccountContext;
import net.simpleframework.organization.account.IAccount;
import net.simpleframework.util.ConvertUtils;
import net.simpleframework.util.LocaleI18n;
import net.simpleframework.util.StringUtils;
import net.simpleframework.web.EFunctionModule;
import net.simpleframework.web.page.IForward;
import net.simpleframework.web.page.component.ComponentParameter;

public class DocuAjaxHandle extends AbstractMgrToolsAction {

	@Override
	public Object getBeanProperty(ComponentParameter compParameter, String beanProperty) {
		if ("jobExecute".equals(beanProperty)) {
			return IJob.sj_account_normal;
		}
		return super.getBeanProperty(compParameter, beanProperty);
	}

	/**
	 * 线程处理
	 * @param compParameter
	 * @return
	 */
	public IForward docuConvert(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {
			@Override
			public void doAction(final Map<String, Object> json) {
				final String[] docuIds = compParameter.getRequestParameter("docuIds").split(",");
				for (final String docuId : docuIds) {
					if (ItSiteUtil.isManage(compParameter, DocuUtils.applicationModule)) {
						try {
							final DocuBean docuBean = DocuUtils.applicationModule.getBean(DocuBean.class, docuId);
							if (docuBean == null) {
								return;
							}
							docuBean.setSuccess(1);
							DocuUtils.applicationModule.doUpdate(new Object[] { "success" }, docuBean);
							// 如果是管理员或者开启自动审核，自动发布
							final boolean autoAudit = "true".equals(CommonUtils.getContent(ECommonType.docu_auto));
							if (autoAudit || OrgUtils.isManagerMember(ItSiteUtil.getUserById(docuBean.getUserId()))) {
								docuBean.setStatus(EDocuStatus.publish);
							}
							DocuUtils.convertDocuThread(docuBean);
						} catch (Exception e) {
						}
					}
				}
			}
		});
	}

	@Override
	public IForward indexRebuild(final ComponentParameter compParameter) {
		DocuUtils.applicationModule.createLuceneManager(compParameter).rebuildAll(true);
		return jsonForward(compParameter, new JsonCallback() {
			@Override
			public void doAction(final Map<String, Object> json) {
				json.put("info", LocaleI18n.getMessage("manager_tools.6"));
			}
		});
	}

	/**
	 * 投票
	 * @param compParameter
	 * @return
	 */
	public IForward docuVote(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {
			@Override
			public void doAction(final Map<String, Object> json) {
				final DocuBean docuBean = DocuUtils.applicationModule.getViewDocuBean(compParameter);
				if (docuBean != null) {
					ICommonBeanAware.Utils.updateVotes(compParameter, DocuUtils.applicationModule.getDataObjectManager(), docuBean, json);
				}
			}
		});
	}

	/**
	 * 删除日志
	 * @param compParameter
	 * @return
	 */
	public IForward docuDelLogDelete(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {
			@Override
			public void doAction(final Map<String, Object> json) {
				final String ids = compParameter.getRequestParameter("dellogs");
				if (StringUtils.hasText(ids)) {
					final ITableEntityManager tMrg = DocuUtils.applicationModule.getDataObjectManager(DocuDelLog.class);
					final String ids_ = StringUtils.join(Arrays.asList(ids.split(",")), ",");
					final ExpressionValue eValue = new ExpressionValue("id in(" + ids_ + ")", null);
					tMrg.deleteTransaction(eValue);
				}
			}
		});
	}

	/**
	 * 申请删除文档
	 * @param compParameter
	 * @return
	 */
	public IForward docuAppDel(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {
			@Override
			public void doAction(final Map<String, Object> json) {
				final DocuBean docuBean = DocuUtils.applicationModule.getViewDocuBean(compParameter);
				final ID userId = ItSiteUtil.getLoginUser(compParameter).getId();
				if (docuBean != null && ItSiteUtil.isManageOrSelf(compParameter, DocuUtils.applicationModule, userId)) {
					if (ItSiteUtil.isManage(compParameter, DocuUtils.applicationModule)) {
						docuBean.setStatus(EDocuStatus.delete_manager);
						DocuUtils.applicationModule.doUpdate(docuBean, new TableEntityAdapter() {
							@Override
							public void afterUpdate(ITableEntityManager manager, Object[] obects) {
								//总数加-1
								DocuUtils.addDocuCounter(-1);
								//删除相关标签
								//								MyTagUtils.deleteRTags(dataObjectValue.getValues());
								//								//删除lucence
								//								DocuUtils.applicationModule.createLuceneManager(compParameter).deleteDocumentBackground(dataObjectValue.getValues());
								//								//删除磁盘文档
								//								final StorageBean storageBean = DocumentConfigMgr.getDocuMgr().getStorageMap().get(docuBean.getPath2());
								//								if (storageBean != null) {
								//									storageBean.deleteFile(DocuUtils.getDatabase(docuBean.getUserId()), docuBean.getFileName());
								//									storageBean.deleteFile(DocuUtils.getDatabase(docuBean.getUserId()), docuBean.getId().toString());
								//								}
								//增加日志
								final DocuDelLog delLog = new DocuDelLog();
								delLog.setDelReason(compParameter.getRequestParameter("delReason"));
								delLog.setTitle(docuBean.getTitle());
								delLog.setUserId(docuBean.getUserId());
								DocuUtils.applicationModule.doUpdate(delLog);
							}
						});
					} else {
						docuBean.setStatus(EDocuStatus.delete_user);
						DocuUtils.applicationModule.doUpdate(new Object[] { "status" }, docuBean, new TableEntityAdapter() {
							@Override
							public void afterUpdate(ITableEntityManager manager, Object[] objects) {
								final DocuDelLog delLog = new DocuDelLog();
								delLog.setTitle(docuBean.getTitle());
								delLog.setUserId(docuBean.getUserId());
								delLog.setDelReason(compParameter.getRequestParameter("appDelReason"));
								delLog.setStatus(true);
								DocuUtils.applicationModule.doUpdate(delLog);
							}
						});
					}
				}
			}
		});
	}

	/**
	 * 真正的删除文档
	 * @param compParameter
	 * @return
	 */
	public IForward docuDeledDelete(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {
			@Override
			public void doAction(final Map<String, Object> json) {
				final String[] docuIds = compParameter.getRequestParameter("deleds").split(",");
				for (final String docuId : docuIds) {
					final DocuBean docuBean = DocuUtils.applicationModule.getBean(DocuBean.class, docuId);
					if (ItSiteUtil.isManage(compParameter, DocuUtils.applicationModule)) {
						DocuUtils.applicationModule.doDelete(docuBean, new TableEntityAdapter() {
							@Override
							public void afterDelete(ITableEntityManager manager, IDataObjectValue dataObjectValue) {
								MyTagUtils.deleteRTags(dataObjectValue.getValues());
								//删除lucence
								DocuUtils.applicationModule.createLuceneManager(compParameter).deleteDocumentBackground(dataObjectValue.getValues());
								//删除磁盘文档
								final StorageBean storageBean = DocumentConfigMgr.getDocuMgr().getStorageMap().get(docuBean.getPath2());
								if (storageBean != null) {
									storageBean.deleteFile(DocuUtils.getDatabase(docuBean.getUserId()), docuBean.getFileName());
									storageBean.deleteFile(DocuUtils.getDatabase(docuBean.getUserId()), docuBean.getId().toString());
								}
							}
						});
					}
				}
			}
		});
	}

	public IForward docuDeledPublish(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {
			@Override
			public void doAction(final Map<String, Object> json) {
				final String docuId = compParameter.getRequestParameter("docuId");
				final DocuBean docuBean = DocuUtils.applicationModule.getBean(DocuBean.class, docuId);
				if (ItSiteUtil.isManage(compParameter, DocuUtils.applicationModule)) {
					docuBean.setStatus(EDocuStatus.publish);
					DocuUtils.applicationModule.doUpdate(docuBean, new TableEntityAdapter() {
						@Override
						public void afterDelete(ITableEntityManager manager, IDataObjectValue dataObjectValue) {
							DocuUtils.addDocuCounter(1);
						}
					});
				}
			}
		});
	}

	/**
	 * 标签
	 * 
	 * @param compParameter
	 * @return
	 */
	public IForward docuTag(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {

			@Override
			public void doAction(final Map<String, Object> json) throws Exception {
				final IDataObjectQuery<MyTagBean> qs = MyTagUtils.layoutTags(compParameter);
				final StringBuffer buf = new StringBuffer();
				MyTagBean tagBean;
				final String id = compParameter.getRequestParameter("id");
				while ((tagBean = qs.next()) != null) {
					if (qs.position() > 8) {
						break;
					}
					buf.append("<a class='os_tag' onclick=\"selectTag('" + id + "',this);\">");
					buf.append(tagBean.getTagText()).append("</a>");
				}
				json.put("rs", buf.toString());
				json.put("id", id);
			}
		});
	}

	/**
	 * 关注
	 * 
	 * @param compParameter
	 * @return
	 */
	public IForward docuAttention(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {

			@Override
			public void doAction(final Map<String, Object> json) throws Exception {
				AbstractAttention.Utils.updateAttention(DocuUtils.docuId, compParameter, DocuBean.class, DocuAttention.class,
						DocuUtils.applicationModule, json);
			}
		});
	}

	/**
	 * 下载
	 * 
	 * @param compParameter
	 * @return
	 */
	public IForward docuDownload(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {

			@Override
			public void doAction(final Map<String, Object> json) throws Exception {
				final DocuBean docuBean = DocuUtils.applicationModule.getBean(DocuBean.class, compParameter.getRequestParameter(DocuUtils.docuId));
				if (docuBean != null) {
					final IUser user = ItSiteUtil.getLoginUser(compParameter);
					json.put("point", docuBean.getPoint());
					json.put("self", docuBean.getUserId().equals2(user.getId()));
					json.put("docuId", compParameter.getRequestParameter("docuId"));
					// 表示该用户已经下载过该文档，不再扣去积分
					if (DocuUtils.applicationModule.queryBean("userId=? and docuId=?", new Object[] { user.getId(), docuBean.getId() },
							DocuLogBean.class).getCount() == 0) {
						if (docuBean.getPoint() > user.account().getPoints()) {
							json.put("act", "您的积分不够，无法下载!");
							return;
						}
						final String path1 = DocuUtils.getDatabase(docuBean.getUserId());
						final StorageBean storageBean = DocumentConfigMgr.getDocuMgr().getStorageMap().get(docuBean.getPath2());
						if (storageBean != null) {
							final InputStream is = storageBean.getInputStream(path1 + docuBean.getFileName());
							if (is == null) {
								json.put("act", "文件已被删除，等待管理员核查!");
								return;
							}
						}
					} else {
						final String path1 = DocuUtils.getDatabase(docuBean.getUserId());
						final StorageBean storageBean = DocumentConfigMgr.getDocuMgr().getStorageMap().get(docuBean.getPath2());
						if (storageBean != null) {
							final InputStream is = storageBean.getInputStream(path1 + docuBean.getFileName());
							if (is == null) {
								json.put("act", "文件已被删除，等待管理员核查!");
								return;
							}
						}
						json.put("self", true);
					}
				}
			}
		});
	}

	/**
	 * 评分
	 * 
	 * @param compParameter
	 * @return
	 */
	public IForward docuStar(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {

			@Override
			public void doAction(final Map<String, Object> json) throws Exception {
				final DocuBean docuBean = DocuUtils.applicationModule.getBean(DocuBean.class, compParameter.getRequestParameter(DocuUtils.docuId));
				if (docuBean != null) {
					synchronized (DocuUtils.applicationModule) {
						final String attributeName = "grades_" + docuBean.getId();
						final boolean grades = ConvertUtils.toBoolean(compParameter.getSessionAttribute(attributeName), false);
						if (!grades) {
							compParameter.setSessionAttribute(attributeName, Boolean.TRUE);
							docuBean.setGradeCounter(docuBean.getGradeCounter() + 1);
							docuBean.statGrade((float) Math.min(Math.max(ConvertUtils.toInt(compParameter.getRequestParameter("grade"), 0), 0), 5));
							DocuUtils.applicationModule.doUpdate(new Object[] { "gradeCounter", "totalGrade" }, docuBean);
							json.put("act", "true");
							json.put("grade", docuBean.getStarGrade());
							json.put("grade1", String.valueOf(docuBean.getTotalGrade()));
							//添加全文索引
							DocuUtils.applicationModule.createLuceneManager(compParameter).objects2DocumentsBackground(docuBean);
						} else {
							json.put("act", "false");
						}
					}
				}
			}
		});
	}

	/**
	 * 删除文档
	 * @param compParameter
	 * @return
	 */
	public IForward docuDelete(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {

			@Override
			public void doAction(final Map<String, Object> json) throws Exception {
				final ID userId = ItSiteUtil.getLoginUser(compParameter).getId();
				final String[] docuIds = compParameter.getRequestParameter("docuIds").split(",");
				for (final String docuId : docuIds) {
					final DocuBean docuBean = DocuUtils.applicationModule.getBean(DocuBean.class, docuId);
					docuBean.setStatus(EDocuStatus.delete_manager);
					DocuUtils.applicationModule.doUpdate(docuBean);
					if (docuBean != null && ItSiteUtil.isManageOrSelf(compParameter, DocuUtils.applicationModule, userId)) {
						//不是管理员,不能删除发布状态和用户申请删除状态
//						if (docuBean.getStatus() == EDocuStatus.publish || docuBean.getStatus() == EDocuStatus.delete_user) {
//							if (!ItSiteUtil.isManage(compParameter, DocuUtils.applicationModule)) {
//								json.put("act", "你没有权限操作。");
//								return;
//							}
//						}
						//总数加-1
						DocuUtils.addDocuCounter(-1);
						//删除相关标签
						MyTagUtils.deleteRTags(new Object[] { docuBean.getId() });
						//删除lucence
						DocuUtils.applicationModule.createLuceneManager(compParameter).deleteDocumentBackground(new Object[] { docuBean.getId() });
						//删除磁盘文档
						//						final StorageBean storageBean = DocumentConfigMgr.getDocuMgr().getStorageMap().get(docuBean.getPath2());
						//						if (storageBean != null) {
						//							storageBean.deleteFile(DocuUtils.getDatabase(docuBean.getUserId()), docuBean.getFileName());
						//							storageBean.deleteFile(DocuUtils.getDatabase(docuBean.getUserId()), docuBean.getId().toString());
						//						}
						//增加日志
						final DocuDelLog delLog = new DocuDelLog();
						delLog.setDelReason(compParameter.getRequestParameter("delReason"));
						delLog.setTitle(docuBean.getTitle());
						delLog.setUserId(docuBean.getUserId());
						DocuUtils.applicationModule.doUpdate(delLog);
						json.put("act", "删除成功!");
					} else {
						json.put("act", "你没有权限操作。");
						break;
					}
				}
			}
		});
	}

	/**
	 * 删除文档log
	 * @param compParameter
	 * @return
	 */
	public IForward docuLogDelete(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {

			@Override
			public void doAction(final Map<String, Object> json) throws Exception {
				final String ids = compParameter.getRequestParameter("logIds");
				if (StringUtils.hasText(ids) && ItSiteUtil.isManage(compParameter, DocuUtils.applicationModule)) {
					final ITableEntityManager tMrg = DocuUtils.applicationModule.getDataObjectManager(DocuLogBean.class);
					final String ids_ = StringUtils.join(Arrays.asList(ids.split(",")), ",");
					final ExpressionValue eValue = new ExpressionValue("id in(" + ids_ + ")", null);
					tMrg.deleteTransaction(eValue);
				}
			}
		});
	}

	/**
	 * 编辑文档
	 * @param compParameter
	 * @return
	 */
	public IForward docuEditSave(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {

			@Override
			public void doAction(final Map<String, Object> json) throws Exception {
				final ID userId = ItSiteUtil.getLoginUser(compParameter).getId();
				final DocuBean docuBean = DocuUtils.applicationModule.getBean(DocuBean.class, compParameter.getRequestParameter(DocuUtils.docuId));
				if (docuBean != null && ItSiteUtil.isManageOrSelf(compParameter, DocuUtils.applicationModule, userId)) {
					final String docu_title = compParameter.getRequestParameter("docu_title");
					final String docu_content = compParameter.getRequestParameter("docu_content");
					final String docu_keyworks = compParameter.getRequestParameter("docu_keyworks");
					final String docu_catalog = compParameter.getRequestParameter("docu_catalog");
					final String docu_code_catalog = compParameter.getRequestParameter("docu_code_catalog");
					final String code_language = compParameter.getRequestParameter("code_language");
					final String docu_function = compParameter.getRequestParameter("docu_function");
					final String docu_point = compParameter.getRequestParameter("docu_point");
					final String docu_free_page = compParameter.getRequestParameter("docu_free_page");
					docuBean.setTitle(docu_title);
					docuBean.setLastUserId(userId);
					docuBean.setContent(docu_content);
					docuBean.setKeyworks(docu_keyworks);
					if (StringUtils.hasText(docu_catalog)) {
						docuBean.setCatalogId(new LongID(docu_catalog));
					}
					if (docuBean.getDocuFunction() != EDocuFunction.docu || ItSiteUtil.isManage(compParameter, DocuUtils.applicationModule)) {
						docuBean.setDocuFunction(EDocuFunction.whichOne(docu_function));
					}
					if (docuBean.getDocuFunction() == EDocuFunction.code) {
						if (StringUtils.hasText(docu_code_catalog)) {
							docuBean.setCodeCatalogId(new LongID(docu_code_catalog));
						}
						docuBean.setLanguage(code_language);
					}
					docuBean.setPoint(ConvertUtils.toInt(docu_point, 0));
					docuBean.setAllowRead(NumberUtils.toDouble(docu_free_page));
					//当文档不是发布状态时
					if (docuBean.getStatus() != EDocuStatus.publish) {
						docuBean.setStatus(EDocuStatus.audit);//文档编辑后改为审核状态
					}
					DocuUtils.applicationModule.doUpdate(docuBean);
				}
			}
		});
	}

	/**
	 * 发布文档
	 * @param compParameter
	 * @return
	 */
	public IForward docuPublish(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {

			@Override
			public void doAction(final Map<String, Object> json) throws Exception {
				final String[] docuIds = compParameter.getRequestParameter("docuIds").split(",");
				for (final String docuId : docuIds) {
					final DocuBean docuBean = DocuUtils.applicationModule.getBean(DocuBean.class, docuId);
					if (docuBean != null && ItSiteUtil.isManage(compParameter, DocuUtils.applicationModule)) {
						//						if (docuBean.getSuccess() == 0) {
						//							json.put("act", "文档还没有转换");
						//							return;
						//						} else if (docuBean.getSuccess() == 1) {
						//							json.put("act", "文档正在转换");
						//							return;
						//						} else if (docuBean.getSuccess() == 3) {
						//							json.put("act", "文档转换失败，重新转换！");
						//							return;
						//						}
						if (docuBean.getStatus() == EDocuStatus.audit) {
							docuBean.setStatus(EDocuStatus.publish);
							docuBean.setSuccess(2);
							DocuUtils.applicationModule.doUpdate(docuBean, new TableEntityAdapter() {
								@Override
								public void afterUpdate(ITableEntityManager manager, Object[] objects) {
									//自己关注自己
									final DocuAttention attention = new DocuAttention();
									attention.setDocuId(docuBean.getId());
									attention.setUserId(docuBean.getUserId());
									try {
										DocuUtils.applicationModule.doUpdate(attention);
									} catch (Exception e) {
									}

									final IAccount account = ItSiteUtil.getAccountById(docuBean.getUserId());
									//发布消息，增加积分
									AccountContext.update(account, "docu_add", docuBean.getId());
									ItSiteUtil.addSpaceLog(account, "用户 " + docuBean.getUserText() + " 上传了-《" + docuBean.getTitle() + "》",
											EFunctionModule.docu, docuBean.getId());
									ItSiteUtil.addAccountLog(account.getId(), "上传文档", docuBean.getPoint(), 0, docuBean.getId());
									//保存标签
									MyTagUtils.syncTags(ETagType.docu, docuBean.getCatalogId(), docuBean.getKeyworks(), docuBean.getId());
									//使总上传文档数+1
									DocuUserBean userBean = DocuUtils.applicationModule.getBeanByExp(DocuUserBean.class, "userId=?",
											new Object[] { docuBean.getUserId() });
									if (userBean == null) {
										userBean = new DocuUserBean();
										userBean.setUserId(docuBean.getUserId());
									}
									userBean.setUpFiles(userBean.getUpFiles() + 1);
									DocuUtils.applicationModule.doUpdate(userBean);
									//总数加+1
									DocuUtils.addDocuCounter(1);
									//添加全文索引
									DocuUtils.applicationModule.createLuceneManager(compParameter).objects2DocumentsBackground(docuBean);
								}
							});
						}
					}
				}
			}
		});
	}

	/**
	 * 文档属性
	 * @param compParameter
	 * @return
	 */
	public IForward docuAttrSave1(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {

			@Override
			public void doAction(final Map<String, Object> json) throws Exception {
				CommonUtils.setContent(ECommonType.docu_auto,
						Boolean.toString(ConvertUtils.toBoolean(compParameter.getRequestParameter("autoAudit"), false)));
				CommonUtils.setContent(ECommonType.converNumber, compParameter.getRequestParameter("converNumber"));
			}
		});
	}

	/**
	 * 高级属性
	 * @param compParameter
	 * @return
	 */
	public IForward docuAttrSave(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {

			@Override
			public void doAction(final Map<String, Object> json) throws Exception {
				final DocuBean docuBean = DocuUtils.applicationModule.getBean(DocuBean.class, compParameter.getRequestParameter(DocuUtils.docuId));
				if (docuBean != null && ItSiteUtil.isManage(compParameter, DocuUtils.applicationModule)) {
					//					if (docuBean.getFileNum() == 0) {
					//						json.put("act", "文档还没有转换");
					//						return;
					//					}
					final EDocuStatus status = docuBean.getStatus();
					docuBean.setStatus(EDocuStatus.valueOf(compParameter.getRequestParameter("docu_status")));
					docuBean.setTtype(EContentType.valueOf(compParameter.getRequestParameter("docu_ttype")));
					final double adminGrade = ConvertUtils.toDouble(compParameter.getRequestParameter("docu_grade"), docuBean.getAdminGrade());
					docuBean.setAdminGrade((float) Math.min(Math.max(adminGrade, 0), 5));
					docuBean.statGrade(docuBean.getTotalGrade());
					DocuUtils.applicationModule.doUpdate(docuBean, new TableEntityAdapter() {
						@Override
						public void afterUpdate(ITableEntityManager manager, Object[] objects) {
							if (status != docuBean.getStatus() && docuBean.getStatus() == EDocuStatus.publish) {
								DocuUtils.publishDocu(docuBean);
								//添加全文索引
								DocuUtils.applicationModule.createLuceneManager(compParameter).objects2DocumentsBackground(docuBean);
							}
						}
					});
				}
			}
		});
	}

	/**
	 * 保存文档
	 */
	public IForward docuSave(final ComponentParameter compParameter) throws Exception {
		return jsonForward(compParameter, new JsonCallback() {

			@Override
			public void doAction(final Map<String, Object> json) throws Exception {
				final ID userId = ItSiteUtil.getLoginUser(compParameter).getId();
				try {
					final String docuId = compParameter.getRequestParameter("docuId");
					final String docu_title = compParameter.getRequestParameter("docu_title");
					final String docu_content = compParameter.getRequestParameter("docu_content");
					final String docu_keyworks = compParameter.getRequestParameter("docu_keyworks");
					final String docu_catalog = compParameter.getRequestParameter("docu_catalog");
					final String docu_code_catalog = compParameter.getRequestParameter("docu_code_catalog");
					final String code_language = compParameter.getRequestParameter("code_language");
					final String docu_function = compParameter.getRequestParameter("docu_function");
					final String docu_point = compParameter.getRequestParameter("docu_point");
					final String docu_free_page = compParameter.getRequestParameter("docu_free_page");
					final DocuBean docuBean = DocuUtils.applicationModule.getBean(DocuBean.class, docuId);
					if (docuBean != null) {
						docuBean.setUserId(userId);
						docuBean.setLastUserId(userId);
						docuBean.setTitle(docu_title);
						docuBean.setContent(docu_content);
						docuBean.setKeyworks(docu_keyworks);
						if (StringUtils.hasText(docu_catalog)) {
							docuBean.setCatalogId(new LongID(docu_catalog));
						}
						if (docuBean.getDocuFunction() != EDocuFunction.docu) {
							docuBean.setDocuFunction(EDocuFunction.whichOne(docu_function));
						}
						if (docuBean.getDocuFunction() == EDocuFunction.code) {
							if (StringUtils.hasText(docu_code_catalog)) {
								docuBean.setCodeCatalogId(new LongID(docu_code_catalog));
							}
							docuBean.setLanguage(code_language);
						}
						docuBean.setPoint(ConvertUtils.toInt(docu_point, 0));
						docuBean.setAllowRead(NumberUtils.toDouble(docu_free_page));
						docuBean.setStatus(EDocuStatus.audit);
						final boolean autoAudit = "true".equals(CommonUtils.getContent(ECommonType.docu_auto));
						final boolean convert = autoAudit || OrgUtils.isManagerMember(ItSiteUtil.getUserById(docuBean.getUserId()));
						if (convert) {
							docuBean.setSuccess(1);
						}
						DocuUtils.applicationModule.doUpdate(docuBean, new TableEntityAdapter() {

							@Override
							public void afterUpdate(ITableEntityManager manager, Object[] objects) {
								if (convert) {
									DocuUtils.convertDocuThread(docuBean);
								}
							}
						});
					}
				} catch (Exception e) {
				}
			}
		});
	}

	@Override
	public IContentApplicationModule getApplicationModule() {
		return DocuUtils.applicationModule;
	}

	@Override
	protected void doStatRebuild() {
		DocuUtils.doStatRebuild();
	}
}
